// src/router/index.js（修正版）
import { createRouter, createWebHistory } from "vue-router";
import LoginView from "../views/LoginView.vue";
import AdminView from "../views/AdminView.vue";
import AdminViewB from "../views/AdminViewB.vue";
import AdminLayout from "../views/AdminLayout.vue";
import PondView from "@/views/PondView.vue";
import FlowerView from "@/views/FlowerView.vue";
import OrchardView from "@/views/OrchardView.vue";
import DeviceView from "@/views/DeviceView.vue";

// 简单的内存存储
export const inMemoryStorage = {
  token: "",
  role: "", // 可能的值："Administrator"（管理员）、"Worker"（工人）
};

// --- 路由守卫定义 ---
// 仅管理员可访问的守卫
const requireOnlyAdmin = (to, from, next) => {
  if (inMemoryStorage.token && inMemoryStorage.role === "Administrator") {
    next(); // 管理员允许访问
  } else if (inMemoryStorage.token && inMemoryStorage.role === "Worker") {
    next("/admin/pond"); // 工人跳转到自己的页面
  } else {
    next("/"); // 未登录跳登录页
  }
};

// 仅工人可访问的守卫
const requireOnlyWorker = (to, from, next) => {
  if (inMemoryStorage.token && inMemoryStorage.role === "Worker") {
    next(); // 工人允许访问
  } else if (
    inMemoryStorage.token &&
    inMemoryStorage.role === "Administrator"
  ) {
    next("/admin"); // 管理员跳转到自己的页面
  } else {
    next("/"); // 未登录跳登录页
  }
};

// 已登录用户跳转守卫（根据角色跳对应首页）
const redirectIfLoggedIn = (to, from, next) => {
  if (inMemoryStorage.token) {
    if (inMemoryStorage.role === "Administrator") {
      next("/admin"); // 管理员跳管理员首页
    } else if (inMemoryStorage.role === "Worker") {
      next("/admin/pond"); // 工人跳工人首页
    }
  } else {
    next(); // 未登录继续留登录页
  }
};

// --- 路由配置 ---
const routes = [
  // 登录页
  {
    path: "/",
    name: "login",
    component: LoginView,
    beforeEnter: redirectIfLoggedIn,
  },

  // 管理后台父路由
  {
    path: "/admin",
    component: AdminLayout,
    children: [
      // 仅管理员可访问的页面
      {
        path: "", // /admin（管理员首页）
        name: "admin",
        component: AdminView,
        beforeEnter: requireOnlyAdmin,
      },
      {
        path: "b", // /admin/b（管理员专属页面）
        name: "adminB",
        component: AdminViewB,
        beforeEnter: requireOnlyAdmin,
      },

      // 仅工人可访问的页面
      {
        path: "pond", // /admin/pond（工人页面）
        name: "pond",
        component: PondView,
        beforeEnter: requireOnlyWorker,
      },
      {
        path: "orchard", // /admin/orchard（工人页面）
        name: "orchard",
        component: OrchardView,
        beforeEnter: requireOnlyWorker,
      },
      {
        path: "flower", // /admin/flower（工人页面）
        name: "flower",
        component: FlowerView,
        beforeEnter: requireOnlyWorker,
      },
      {
        path: "device", // /admin/flower（工人页面）
        name: "device",
        component: DeviceView,
        beforeEnter: requireOnlyWorker,
      },
    ],
  },

  // 404 重定向
  {
    path: "/:pathMatch(.*)*",
    redirect: "/",
  },
];

// 创建路由实例
const router = createRouter({
  history: createWebHistory(),
  routes,
});

export default router;
